﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using System.Net;
using System.Data;


public partial class Admin_Components_MasterData_News : System.Web.UI.UserControl
{
    DBDataContext db;
    DatabaseHelper helper;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Session["Username"] != null)
            {
                ResetForm();
            }
        }
    }
    private void loadData( ProNews pro)
    {
        try
        {
            int PageNumber = gvData.CurrentPageIndex + 1;
            int PageSize = gvData.PageSize;

            helper = new DatabaseHelper();
            System.Data.Common.DbParameter paramNewsID = helper.Parameter;
            paramNewsID.ParameterName = "NewsID";
            paramNewsID.DbType = DbType.Int32;
            paramNewsID.Value = -1;
            helper.AddParameter(paramNewsID);

            System.Data.Common.DbParameter paramNewsType = helper.Parameter;
            paramNewsType.ParameterName = "NewsType";
            paramNewsType.DbType = DbType.String;
            paramNewsType.Value = pro.strNewsTypeSearch;
            helper.AddParameter(paramNewsType);

            System.Data.Common.DbParameter paramTitle = helper.Parameter;
            paramTitle.ParameterName = "Title";
            paramTitle.DbType = DbType.String;
            paramTitle.Value = pro.strTitleSearch;
            helper.AddParameter(paramTitle);

            System.Data.Common.DbParameter paramStartDate = helper.Parameter;
            paramStartDate.ParameterName = "StartDate";
            paramStartDate.DbType = DbType.String;
            paramStartDate.Value = pro.strStartDate;
            helper.AddParameter(paramStartDate);

            System.Data.Common.DbParameter paramEndDate = helper.Parameter;
            paramEndDate.ParameterName = "EndDate";
            paramEndDate.DbType = DbType.String;
            paramEndDate.Value = pro.strEndDate;
            helper.AddParameter(paramEndDate);

            System.Data.Common.DbParameter paramPageNumber = helper.Parameter;
            paramPageNumber.ParameterName = "PageNumber";
            paramPageNumber.DbType = DbType.Int32;
            paramPageNumber.Value = PageNumber;
            helper.AddParameter(paramPageNumber);

            System.Data.Common.DbParameter paramPageSize = helper.Parameter;
            paramPageSize.ParameterName = "PageSize";
            paramPageSize.DbType = DbType.Int32;
            paramPageSize.Value = PageSize;
            helper.AddParameter(paramPageSize);
            DataTable dt = helper.ExecuteDataTable("Admin_GetNews", CommandType.StoredProcedure, ConnectionState.CloseOnExit);
            if (dt.Rows.Count > 0)
            {
                gvData.Height = 250;
                gvData.ClientSettings.Scrolling.AllowScroll = true;
                gvData.ClientSettings.Scrolling.UseStaticHeaders = true;
                gvData.VirtualItemCount = Convert.ToInt32(dt.Rows[0]["TotalRows"]);
                div_TotalRows.InnerText = "Kết quả tìm kiếm: " + dt.Rows[0]["TotalRows"].ToString();
                gvData.DataSource = dt;
            }
            else
            {
                gvData.DataSource = new DataTable();
                div_TotalRows.InnerText = "Kết quả tìm kiếm: 0";
            }

            gvData.DataBind();
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("News Page-loadData:" + ex.Message);
        }
    }   
    private void fillData(ProNews pro)
    {
        try
        {
            txtTitle.Text = pro.strTitle;
            txtContentShort.Text = pro.strShortContent;
            RadEditorContent.Content = pro.strContent;
            cbNewsType.SelectedValue = pro.strNewsType;
            txtSortOrder.Text = String.Format("{0:#,#.##}", pro.iSortOrder);
            hidOldImagePath.Value = pro.strOldImagePath;
            img.ImageUrl = Utils.getUrlImage() + pro.strImagePath;
            img.Visible = true;
            btnCancel.Enabled = true;
            btnSave.Enabled = true;
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("News Page-fillData:" + ex.Message);
        }
    }
    private void ResetForm()
    {
        try
        {
            txtTitle.Text = null;
            txtContentShort.Text = null;
            RadEditorContent.Content = "";
            rtpFromDateSearch.SelectedDate = DateTime.Now.Date;
            rtpToDateSearch.SelectedDate = DateTime.Now.Date;
            txtTitleSearch.Text = "";
            txtSortOrder.Text = "";
            img.Visible = false;
            ViewState["NewsID"] = null;
            hidOldImagePath.Value = "";
            img.Visible = false;
            btnCancel.Enabled = false;
            
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("News Page-Reset:" + ex.Message);
        }
    }
    private bool SaveNews(ProNews pro)
    {
        db = new DBDataContext();
        db.Connection.Open();
        try
        {
            if (ViewState["NewsID"] == null)//Insert I
            {
                New objNew = new New();
                objNew.Title = pro.strTitle;
                objNew.ContentShort = pro.strShortContent;
                objNew.Content = pro.strContent;
                objNew.CreatedDateTime = DateTime.Now;
                objNew.LastUpdatedDateTime = DateTime.Now;
                objNew.CreatedBy = pro.strCreatedBy;
                objNew.LastUpdatedBy = pro.strLastUpdatedBy;
                objNew.NewsType = pro.strNewsType;
                objNew.ImagePath = pro.strImagePath;
                objNew.SortOrder = pro.iSortOrder;
                objNew.Status = 'A';
                db.Insert<New>(objNew);
                db.SubmitChanges();
                ViewState["NewsID"] = objNew.ID;

            }
            else {//UPDATE
                int iNewsID = Convert.ToInt32(ViewState["NewsID"]);
                New objNew = db.News.FirstOrDefault(x => x.ID == iNewsID);
                objNew.Title = pro.strTitle;
                objNew.ContentShort = pro.strShortContent;
                objNew.Content = pro.strContent;
                objNew.LastUpdatedDateTime = DateTime.Now;
                objNew.LastUpdatedBy = pro.strLastUpdatedBy;
                objNew.NewsType = pro.strNewsType;
                objNew.ImagePath = pro.strImagePath;
                objNew.SortOrder = pro.iSortOrder;
                
                db.Update<New>(objNew);
                db.SubmitChanges();
            }
            db.Connection.Close();
            return true;
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("News Page-SaveNews:" + ex.Message);
            return false;
        }
    }
    private void getDataSearch()
    {
        ProNews pro = new ProNews();
        pro.strNewsTypeSearch = Utils.KillChars(cbNewsTypeSearch.SelectedValue);
        pro.strTitleSearch = Utils.KillChars(txtTitle.Text.Trim());
        pro.strStartDate = Utils.KillChars(this.rtpFromDateSearch.SelectedDate == null ? "" : String.Format("{0:dd/MM/yyyy}", this.rtpFromDateSearch.SelectedDate));
        pro.strEndDate = Utils.KillChars(this.rtpToDateSearch.SelectedDate == null ? "" : String.Format("{0:dd/MM/yyyy}", this.rtpToDateSearch.SelectedDate));
        loadData(pro);
        
    }
    #region Properties

    public class ProNews
    {
        public string  strTitle { get; set; }
        public string strShortContent { get; set; }
        public string strImagePath { get; set; }
        public string strOldImagePath { get; set; }
        public string strContent { get; set; }
        public DateTime CreatedDateTime { get; set; }
        public DateTime UpdatedDateTime { get; set; }
        public string strCreatedBy { get; set; }
        public string strNewsType { get; set; }
        public char cStatus { get; set; }
        public string strLastUpdatedBy { get; set; }
        public int? iID { get; set; }
        public int iSortOrder { get; set; }

        public string strStartDate { get; set; }
        public string strEndDate { get; set; }
        public string strTitleSearch { get; set; }
        public string strNewsTypeSearch { get; set; }
    }
    #endregion End Properties
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        try
        {
            gvData.Height = 250;
            gvData.Visible = true;
            getDataSearch();
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("News Page-btnSearch_Click:" + ex.Message);
        }
    }
    protected void btnNew_Click(object sender, EventArgs e)
    {
        ResetForm();
    }
    protected void gvData_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
    {
        try
        {
            if (RadPageView3.Selected)
            {
                TabStrip1.SelectedIndex = 2;
                gvData.Height = 250;
                gvData.Visible = true;
                getDataSearch();
            }
            else
            {
                gvData.DataSource = new DataTable();
            }
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("News Page-gvData_NeedDataSource:" + ex.Message);
        }
    }
    protected void gvData_ItemCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
    {
        try
        {
            ProNews pro = new ProNews();
            string commandName = e.CommandName;
            int iNewID = Convert.ToInt32(e.CommandArgument.ToString());//Lay ID 
            helper = new DatabaseHelper();
            if (commandName == "EditItem")
            {
                RadPageView1.Selected = true;
                TabStrip1.SelectedIndex = 0;
                System.Data.Common.DbParameter paramNewsID = helper.Parameter;
                paramNewsID.ParameterName = "NewsID";
                paramNewsID.DbType = DbType.Int32;
                paramNewsID.Value = iNewID;
                helper.AddParameter(paramNewsID);
                DataTable dt = helper.ExecuteDataTable("Admin_GetNews", CommandType.StoredProcedure, ConnectionState.CloseOnExit);
                if (dt.Rows.Count > 0)
                {
                    pro.strTitle = dt.Rows[0]["Title"].ToString();
                    pro.strShortContent = dt.Rows[0]["ContentShort"].ToString();
                    pro.strNewsType = dt.Rows[0]["NewsType"].ToString();
                    pro.strContent = dt.Rows[0]["Content"].ToString();
                    pro.iSortOrder = Convert.ToInt32(dt.Rows[0]["SortOrder"].ToString());
                    pro.strImagePath = dt.Rows[0]["ImagePath"].ToString() == "" ? "/NoImage.jpg" : dt.Rows[0]["ImagePath"].ToString();
                    pro.strOldImagePath = dt.Rows[0]["ImagePath"].ToString();
                    fillData(pro);
                    ViewState["NewsID"] = iNewID;
                }
            }
            else if (commandName == "DeleteItem")
            {
                db = new DBDataContext();
                db.Connection.Open();
                New objNew = db.News.FirstOrDefault(x => x.ID == iNewID);

                objNew.LastUpdatedDateTime = DateTime.Now;
                objNew.LastUpdatedBy = pro.strLastUpdatedBy;
                objNew.Status = 'I';

                db.Update<New>(objNew);
                db.SubmitChanges();
                db.Connection.Close();
                ResetForm();

                var cus = (from c in db.News
                           where c.ID == iNewID
                           select c).FirstOrDefault();
                Utils.DeleteFileFromServer(cus.ImagePath);
                JavascriptUtil.LoadMessage(UpdatePanel1, true, "Xóa tin thành công!");
                gvData.Rebind();
            }
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("News Page-gvData_ItemCommand:" + ex.Message);
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Thông báo lỗi: Xóa không thành công!");
        }
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            if (Session["Username"] != null)
            {
                ProNews pro = new ProNews();
                pro.strTitle = Utils.KillChars((txtTitle.Text.Trim()));
                pro.strShortContent = Utils.KillChars(txtContentShort.Text.Trim());
                pro.strContent = RadEditorContent.Content.Trim();
                pro.strCreatedBy = Session["Username"].ToString();
                pro.strLastUpdatedBy = Session["Username"].ToString();
                pro.strNewsType = cbNewsType.SelectedValue.ToString() == "" ? "E" : cbNewsType.SelectedValue.ToString();
                pro.iSortOrder = Utils.KillChars((txtSortOrder.Text.Trim())) == "" ? 0 : Convert.ToInt32(Utils.KillChars((txtSortOrder.Text.Trim())));
                //Validate Data
                if (String.IsNullOrEmpty(pro.strTitle))
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng nhập tiêu đề!");
                    return;
                }
                if (String.IsNullOrEmpty(pro.strShortContent))
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng nhập nội dung ngắn gọn!");
                    return;
                }
                if (String.IsNullOrEmpty(pro.strContent))
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng nhập nội dung chi tiết!");
                    return;
                }
                //Luu hinh vao Disk
                if (fuImagePath.HasFile)
                {
                    FileInfo f = new FileInfo(fuImagePath.FileName);
                    if (f != null && (f.Extension.ToLower() != ".gif" && f.Extension.ToLower() != ".jpg" && f.Extension.ToLower() != ".jpeg" && f.Extension.ToLower() != ".png"))
                    {
                        JavascriptUtil.LoadMessage(UpdatePanel1, false, "Chỉ được upload file dạng .gif, .jpg, .jpeg, .png");
                        return;
                    }
                    if (f != null && fuImagePath.FileBytes.Length > (512 * 1024))
                    {
                        JavascriptUtil.LoadMessage(UpdatePanel1, false, "Dung lượng hình ảnh không quá 500kb");
                        return;
                    }
                    //Delete file cu
                    if (!string.IsNullOrEmpty(hidOldImagePath.Value))
                        Utils.DeleteFileFromServer(hidOldImagePath.Value);

                    string strPath = "/Upload/News/";
                    pro.strImagePath = strPath + Path.GetFileName(fuImagePath.FileName);
                    Utils.UploadFileToFTP(fuImagePath, strPath);
                }
                else
                {
                    if (!string.IsNullOrEmpty(hidOldImagePath.Value))
                        pro.strImagePath = hidOldImagePath.Value;
                }
                //End luu hinh vao Disk
                if (SaveNews(pro))
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, true, "Lưu tin thành công!");
                    this.btnSave.Enabled = false;
                }
                else
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Thông báo lỗi: Lưu không thành công, vui lòng kiểm tra dữ liệu!");
                }
            }
        }
        catch (Exception ex)
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Thông báo lỗi: Lưu không thành công, vui lòng kiểm tra dữ liệu!");
            ControlUtil.LogError("News Page-btnSave_Click:" + ex.Message);
        }
    }
    protected void btnRefresh_Click(object sender, EventArgs e)
    {
        getDataSearch();
    }
}
